package com.igeek.ssm.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/2/9 14:41
 */
public class WebInitializer implements WebApplicationInitializer {

    /**
     * Tomcat一启动加载
     * @param servletContext  上下文对象
     * @throws ServletException
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //具备Web环境的IOC容器
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        //注册JavaConfig配置类
        ac.register(new Class[]{MyBatisConfig.class , SpringMVCConfig.class , ThymeleafTemplateConfig.class});

        //在上下文中配置编码集过滤器  处理POST方式乱码
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
        //配置过滤路径
        filterRegistration.addMappingForUrlPatterns(null , true , "/*");

        //在IOC容器中，设置上下文对象
        ac.setServletContext(servletContext);

        //前端控制器
        ServletRegistration.Dynamic servletRegistration = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(ac));
        //前端控制器处理的请求url
        //servletRegistration.addMapping("*.action");
        //设置前端控制器处理的请求  RESTFul风格 HTTP动词 POST、GET、PUT、DELETE
        servletRegistration.addMapping("/");
        //随着Tomcat容器启动而加载
        servletRegistration.setLoadOnStartup(1);
    }
}
